<template>
    <div class="form-generator-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card class="box-card" header="表单配置">
                    <el-form :model="formConfig" label-width="120px">
                        <el-form-item label="表单标题">
                            <el-input v-model="formConfig.title"></el-input>
                        </el-form-item>

                        <el-form-item label="标签宽度">
                            <el-input-number v-model="formConfig.labelWidth" :min="80" :max="300"
                                step="20"></el-input-number>
                        </el-form-item>

                        <el-form-item label="表单尺寸">
                            <el-radio-group v-model="formConfig.size">
                                <el-radio label="default">默认</el-radio>
                                <el-radio label="medium">中等</el-radio>
                                <el-radio label="small">小型</el-radio>
                                <el-radio label="mini">迷你</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="表单Model">
                            <el-input v-model="formConfig.model" placeholder="默认值: temp"></el-input>
                        </el-form-item>

                        <el-form-item label="表单Ref">
                            <el-input v-model="formConfig.ref" placeholder="默认值: form"></el-input>
                        </el-form-item>

                        <el-form-item label="提交函数">
                            <el-input v-model="formConfig.submitFunction" placeholder="默认值: createData"></el-input>
                        </el-form-item>
                    </el-form>

                    <el-divider content-position="left">表单字段配置</el-divider>

                    <el-table :data="formFields" stripe border @row-click="handleRowClick">
                        <el-table-column prop="fieldKey" label="字段Key"></el-table-column>
                        <el-table-column prop="fieldName" label="字段名"></el-table-column>
                        <el-table-column prop="fieldType" label="字段类型"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary"
                                    @click="editField(scope.$index, scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="deleteField(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-row style="margin-top: 20px;">
                        <el-col :span="24" style="text-align: right;">
                            <el-button type="primary" @click="addField">添加字段</el-button>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="12">
                <el-card class="box-card" header="生成代码">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="Vue 模板" name="template">
                            <el-input type="textarea" :rows="20" v-model="generatedTemplate" readonly></el-input>
                        </el-tab-pane>
                        <el-tab-pane label="JavaScript" name="script">
                            <el-input type="textarea" :rows="20" v-model="generatedScript" readonly></el-input>
                        </el-tab-pane>
                        <el-tab-pane label="完整代码" name="full">
                            <el-input type="textarea" :rows="20" v-model="generatedFullCode" readonly></el-input>
                        </el-tab-pane>
                    </el-tabs>

                    <el-row style="margin-top: 20px;">
                        <el-col :span="24" style="text-align: right;">
                            <el-button type="success" @click="copyCode('template')">复制模板</el-button>
                            <el-button type="success" @click="copyCode('script')">复制脚本</el-button>
                            <el-button type="success" @click="copyCode('full')">复制完整代码</el-button>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>

        <!-- 字段配置对话框 -->
        <el-dialog :visible.sync="fieldDialogVisible" title="字段配置">
            <el-form :model="currentField" label-width="120px">
                <el-form-item label="字段Key" :rules="{ required: true, message: '请输入字段Key', trigger: 'blur' }">
                    <el-input v-model="currentField.fieldKey"></el-input>
                </el-form-item>

                <el-form-item label="字段名" :rules="{ required: true, message: '请输入字段名', trigger: 'blur' }">
                    <el-input v-model="currentField.fieldName"></el-input>
                </el-form-item>

                <el-form-item label="字段类型">
                    <el-select v-model="currentField.fieldType" placeholder="请选择字段类型" @change="handleFieldTypeChange">
                        <el-option v-for="type in fieldTypes" :key="type.value" :label="type.label"
                            :value="type.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="是否必填">
                    <el-switch v-model="currentField.required"></el-switch>
                </el-form-item>

                <el-form-item label="校验类型" v-if="currentField.required">
                    <el-select v-model="currentField.validateType" placeholder="请选择校验类型">
                        <el-option v-for="type in validateTypes" :key="type.value" :label="type.label"
                            :value="type.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="占位文本">
                    <el-input v-model="currentField.placeholder"></el-input>
                </el-form-item>

                <!-- 选项配置 - 仅对需要选项的字段类型显示 -->
                <el-form-item label="选项配置" v-if="['select', 'radio', 'checkbox'].includes(currentField.fieldType)">
                    <el-table :data="currentField.options" stripe border>
                        <el-table-column prop="id" label="选项ID"></el-table-column>
                        <el-table-column prop="name" label="选项名称"></el-table-column>
                        <el-table-column label="默认选中" width="120">
                            <template slot-scope="scope">
                                <el-checkbox v-model="scope.row.checked"></el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120">
                            <template slot-scope="scope">
                                <el-button size="mini" type="danger" @click="deleteOption(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-row style="margin-top: 10px;">
                        <el-col :span="8">
                            <el-input v-model="newOption.id" placeholder="选项ID"></el-input>
                        </el-col>
                        <el-col :span="8">
                            <el-input v-model="newOption.name" placeholder="选项名称"></el-input>
                        </el-col>
                        <el-col :span="8">
                            <el-button type="primary" @click="addOption">添加选项</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="fieldDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveField">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeTab: 'full',
            formConfig: {
                title: '表单标题',
                labelWidth: 120,
                size: 'default',
                model: 'temp',
                ref: 'form',
                submitFunction: 'createData'
            },
            formFields: [],
            fieldDialogVisible: false,
            currentField: {
                fieldKey: '',
                fieldName: '',
                fieldType: 'input',
                required: false,
                validateType: 'string',
                placeholder: '',
                options: []
            },
            newOption: {
                id: '',
                name: '',
                checked: false
            },
            fieldTypes: [
                { value: 'input', label: '输入框' },
                { value: 'textarea', label: '文本域' },
                { value: 'select', label: '下拉选择' },
                { value: 'radio', label: '单选框' },
                { value: 'checkbox', label: '复选框' },
                { value: 'date', label: '日期选择' },
                { value: 'time', label: '时间选择' },
                { value: 'datetime', label: '日期时间选择' }
            ],
            validateTypes: [
                { value: 'string', label: '字符串' },
                { value: 'number', label: '数字' },
                { value: 'boolean', label: '布尔值' },
                { value: 'array', label: '数组' },
                { value: 'object', label: '对象' },
                { value: 'email', label: '邮箱' },
                { value: 'url', label: 'URL' }
            ],
            copySuccessMsg: ''
        }
    },
    computed: {
        generatedTemplate() {
            let template = `<template>\n  <el-form :model="${this.formConfig.model}" :rules="rules" label-width="${this.formConfig.labelWidth}px" size="${this.formConfig.size}" ref="${this.formConfig.ref}">\n`;

            this.formFields.forEach(field => {
                const requiredMark = field.required ? '<span class="el-form-item__required">*</span>' : '';
                template += `    <el-form-item label="${requiredMark}${field.fieldName}" prop="${field.fieldKey}">\n`;

                switch (field.fieldType) {
                    case 'input':
                        template += `      <el-input v-model="${this.formConfig.model}.${field.fieldKey}" placeholder="${field.placeholder || `请输入${field.fieldName}`}"></el-input>\n`;
                        break;
                    case 'textarea':
                        template += `      <el-input type="textarea" v-model="${this.formConfig.model}.${field.fieldKey}" placeholder="${field.placeholder || `请输入${field.fieldName}`}"></el-input>\n`;
                        break;
                    case 'select':
                        template += `      <el-select v-model="${this.formConfig.model}.${field.fieldKey}" placeholder="${field.placeholder || `请选择${field.fieldName}`}">\n`;
                        if (field.options && field.options.length) {
                            template += `        <el-option v-for="item in ${field.fieldKey}Arr" :key="item.id" :label="item.name" :value="item.id"></el-option>\n`;
                        } else {
                            template += `        <el-option label="选项1" value="option1"></el-option>\n`;
                            template += `        <el-option label="选项2" value="option2"></el-option>\n`;
                        }
                        template += `      </el-select>\n`;
                        break;
                    case 'radio':
                        template += `      <el-radio-group v-model="${this.formConfig.model}.${field.fieldKey}">\n`;
                        if (field.options && field.options.length) {
                            template += `        <el-radio v-for="item in ${field.fieldKey}Arr" :key="item.id" :label="item.id">{{ item.name }}</el-radio>\n`;
                        } else {
                            template += `        <el-radio label="option1">选项1</el-radio>\n`;
                            template += `        <el-radio label="option2">选项2</el-radio>\n`;
                        }
                        template += `      </el-radio-group>\n`;
                        break;
                    case 'checkbox':
                        template += `      <el-checkbox-group v-model="${this.formConfig.model}.${field.fieldKey}">\n`;
                        if (field.options && field.options.length) {
                            template += `        <el-checkbox v-for="item in ${field.fieldKey}Arr" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>\n`;
                        } else {
                            template += `        <el-checkbox label="option1">选项1</el-checkbox>\n`;
                            template += `        <el-checkbox label="option2">选项2</el-checkbox>\n`;
                        }
                        template += `      </el-checkbox-group>\n`;
                        break;
                    case 'date':
                        template += `      <el-date-picker v-model="${this.formConfig.model}.${field.fieldKey}" type="date" placeholder="${field.placeholder || `请选择${field.fieldName}`}"></el-date-picker>\n`;
                        break;
                    case 'time':
                        template += `      <el-time-picker v-model="${this.formConfig.model}.${field.fieldKey}" type="time" placeholder="${field.placeholder || `请选择${field.fieldName}`}"></el-time-picker>\n`;
                        break;
                    case 'datetime':
                        template += `      <el-date-picker v-model="${this.formConfig.model}.${field.fieldKey}" type="datetime" placeholder="${field.placeholder || `请选择${field.fieldName}`}"></el-date-picker>\n`;
                        break;
                }

                template += `    </el-form-item>\n`;
            });

            template += `    <el-form-item>\n`;
            template += `      <el-button type="primary" @click="${this.formConfig.submitFunction}">提交</el-button>\n`;
            template += `      <el-button @click="resetForm">重置</el-button>\n`;
            template += `    </el-form-item>\n`;
            template += `  </el-form>\n</template>`;

            return template;
        },

        generatedScript() {
            let script = `<script>\nexport default {\n  data() {\n    return {\n      ${this.formConfig.model}: {\n`;

            this.formFields.forEach(field => {
                let defaultValue = '';

                switch (field.fieldType) {
                    case 'input':
                    case 'textarea':
                    case 'select':
                    case 'radio':
                    case 'date':
                    case 'time':
                    case 'datetime':
                        // 检查是否有默认值
                        const defaultOption = field.options && field.options.find(option => option.checked);
                        defaultValue = defaultOption ? `'${defaultOption.id}'` : "''";
                        break;
                    case 'checkbox':
                        // 多选框的默认值是数组
                        const defaultOptions = field.options && field.options.filter(option => option.checked).map(option => `'${option.id}'`);
                        defaultValue = defaultOptions && defaultOptions.length ? `[${defaultOptions.join(', ')}]` : '[]';
                        break;
                    default:
                        defaultValue = "''";
                }

                script += `        ${field.fieldKey}: ${defaultValue},\n`;
            });

            script += `      },\n`;

            // 添加选项数组定义
            script += `      // 选项数组\n`;
            this.formFields.forEach(field => {
                if (['select', 'radio', 'checkbox'].includes(field.fieldType) && field.options && field.options.length) {
                    script += `      ${field.fieldKey}Arr: [\n`;
                    field.options.forEach(option => {
                        script += `        { id: '${option.id}', name: '${option.name}' },\n`;
                    });
                    script += `      ],\n`;
                }
            });

            script += `      rules: {\n`;

            this.formFields.forEach(field => {
                if (field.required) {
                    let validateRule = `        ${field.fieldKey}: [\n          { required: true, message: '请${field.fieldType.includes('select') || field.fieldType.includes('date') || field.fieldType.includes('time') ? '选择' : '输入'}${field.fieldName}', trigger: 'blur' }`;

                    if (field.validateType && field.validateType !== 'string') {
                        validateRule += `,\n          { type: '${field.validateType}', message: '${field.fieldName}格式不正确', trigger: 'change' }`;
                    }

                    validateRule += `\n        ],\n`;
                    script += validateRule;
                }
            });

            script += `      }\n    }\n  },\n  methods: {\n    ${this.formConfig.submitFunction}() {\n      this.$refs.${this.formConfig.ref}.validate(valid => {\n        if (valid) {\n          this.$message.success('表单提交成功');\n          console.log('表单数据:', this.${this.formConfig.model});\n          // 这里可以添加表单提交逻辑\n        } else {\n          this.$message.error('表单验证失败');\n          return false;\n        }\n      });\n    },\n    resetForm() {\n      this.$refs.${this.formConfig.ref}.resetFields();\n    }\n  }\n}`;

            return script;
        },

        generatedFullCode() {
            return `${this.generatedTemplate}\n\n${this.generatedScript}`;
        }
    },
    methods: {
        addField() {
            this.currentField = {
                fieldKey: '',
                fieldName: '',
                fieldType: 'input',
                required: false,
                validateType: 'string',
                placeholder: '',
                options: []
            };
            this.fieldDialogVisible = true;
        },

        editField(index, row) {
            this.currentField = Object.assign({}, row);
            // 确保选项数组存在
            if (!this.currentField.options) {
                this.currentField.options = [];
            }
            this.fieldDialogVisible = true;
        },

        deleteField(index) {
            this.$confirm('确定删除该字段吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.formFields.splice(index, 1);
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                // 用户取消操作
            });
        },

        handleFieldTypeChange() {
            // 当字段类型变更时，如果不是需要选项的类型，清空选项
            if (!['select', 'radio', 'checkbox'].includes(this.currentField.fieldType)) {
                this.currentField.options = [];
            }
        },

        addOption() {
            if (!this.newOption.id || !this.newOption.name) {
                this.$message.error('选项ID和选项名称不能为空');
                return;
            }

            // 检查是否已存在相同ID的选项
            const exists = this.currentField.options.some(option => option.id === this.newOption.id);
            if (exists) {
                this.$message.error('已存在相同ID的选项');
                return;
            }

            this.currentField.options.push({
                id: this.newOption.id,
                name: this.newOption.name,
                checked: this.newOption.checked
            });

            // 清空输入框
            this.newOption = {
                id: '',
                name: '',
                checked: false
            };
        },

        deleteOption(index) {
            this.currentField.options.splice(index, 1);
        },

        saveField() {
            if (!this.currentField.fieldKey || !this.currentField.fieldName) {
                this.$message.error('字段Key和字段名不能为空');
                return;
            }

            // 对于需要选项的字段类型，检查是否有选项
            if (['select', 'radio', 'checkbox'].includes(this.currentField.fieldType) &&
                (!this.currentField.options || this.currentField.options.length === 0)) {
                this.$message.error('请为该字段添加选项');
                return;
            }

            const fieldIndex = this.formFields.findIndex(field => field.fieldKey === this.currentField.fieldKey);

            if (fieldIndex > -1) {
                // 更新现有字段
                this.formFields.splice(fieldIndex, 1, this.currentField);
            } else {
                // 添加新字段
                this.formFields.push(Object.assign({}, this.currentField));
            }

            this.fieldDialogVisible = false;
            this.$message({
                type: 'success',
                message: '字段配置保存成功!'
            });
        },

        copyCode(type) {
            let textToCopy = '';
            let message = '';

            switch (type) {
                case 'template':
                    textToCopy = this.generatedTemplate;
                    message = '模板代码复制成功!';
                    break;
                case 'script':
                    textToCopy = this.generatedScript;
                    message = '脚本代码复制成功!';
                    break;
                case 'full':
                    textToCopy = this.generatedFullCode;
                    message = '完整代码复制成功!';
                    break;
            }

            this.copyToClipboard(textToCopy).then(() => {
                this.$message({
                    type: 'success',
                    message: message
                });
            }).catch(err => {
                this.$message({
                    type: 'error',
                    message: '复制失败，请手动复制'
                });
                console.error('复制失败:', err);
            });
        },

        copyToClipboard(text) {
            return navigator.clipboard.writeText(text);
        },

        handleRowClick(row) {
            // 点击行时编辑字段
            const index = this.formFields.findIndex(field => field.fieldKey === row.fieldKey);
            if (index > -1) {
                this.editField(index, row);
            }
        }
    }
}
</script>

<style scoped>
.box-card {
    min-height: 600px;
}

.el-table {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}

.copy-button {
    margin-left: 10px;
}
</style>